package com.recource.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.recource.annonation.Login;
import com.recource.domain.*;
import com.recource.ro.ResourceRO;
import com.recource.ro.UserRO;
import com.recource.util.HostHolder;
import com.recource.util.SystemUtil;
import com.recource.vo.PageVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.recource.dao.*;
import com.recource.ro.PageRO;
import com.recource.vo.ResourceVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

@Controller
@RequestMapping("/admin")
@Transactional(rollbackFor = Exception.class)
@Login
public class AdminController {

    @Autowired
    HostHolder hostHolder;

    @Autowired
    private UserDao userDao;

    @Autowired
    private FileDao fileDao;

    @Value("${file.root}")
    private String root;

    @Value("${system.previewUrl}")
    private String url;


    @RequestMapping("/index")
    public String index(){
        return "/admin/index";
    }

    @RequestMapping("/user/add.html")
    public String addHtml(){
        return "/admin/user/detail";
    }

    @RequestMapping("/user/page")
    public ModelAndView list(PageRO<User> ro){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/user/list");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(ro.getSearch())){
            wrapper.like(User::getUsername, ro.getSearch());
        }
        PageRO<User> userPageRO = userDao.selectPage(ro, wrapper);
        modelAndView.addObject("page", userPageRO);
        return modelAndView;
    }

    @RequestMapping("/user/detail")
    public ModelAndView detail(String id){
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, id);
        User user = userDao.selectOne(wrapper);
        if(user == null){
            throw new RuntimeException("用户不存在");
        }
        modelAndView.setViewName("/admin/user/detail");
        modelAndView.addObject("user", user);
        return modelAndView;
    }

    @RequestMapping("/user/update")
    public ModelAndView update(UserRO ro){
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if(Objects.nonNull(ro.getId())){
            wrapper.eq(User::getId, ro.getId());
            User user = userDao.selectOne(wrapper);
            if(user == null){
                throw new RuntimeException("用户不存在");
            }
            user.setUsername(ro.getUsername());
            user.setUserType(ro.getUserType());
            user.setPhone(ro.getPhone());
            userDao.updateById(user);
        }else{
            wrapper.eq(User::getUsername, ro.getUsername());
            User user = userDao.selectOne(wrapper);
            if(user != null){
                throw new RuntimeException("用户名已经存在了");
            }
            User user1 = new User();
            String salt = UUID.randomUUID().toString().substring(0, 5);
            user1.setSalt(salt);
            StringBuilder sb = new StringBuilder();
            try {
                String password = DigestUtils.md5DigestAsHex((sb.append(salt).append(ro.getPassword())).toString().getBytes());
                user1.setPassword(password);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            user1.setPhone(ro.getPhone());
            user1.setUserType(ro.getUserType());
            user1.setUsername(ro.getUsername());
            userDao.insert(user1);
        }
        modelAndView.setViewName("redirect:/admin/user/page");
        return modelAndView;
    }

    @RequestMapping("/user/delete")
    public ModelAndView update(int id){
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, id);
        User user = userDao.selectOne(wrapper);
        if(user == null){
            throw new RuntimeException("用户不存在");
        }
        userDao.deleteById(user);
        modelAndView.setViewName("redirect:/admin/user/page");
        return modelAndView;
    }


    //添加研究方向
    @RequestMapping("/design/add.html")
    public String addDesignhtml(){
        return "/admin/design/detail";
    }

    @Autowired
    DesignDao designDao;

    @RequestMapping("/design/update")
    public String adddesign(Design design){
        User user = hostHolder.getUser();
        if(Objects.nonNull(design.getId())){
            LambdaQueryWrapper<Design> designLambdaQueryWrapper = new LambdaQueryWrapper<>();
            designLambdaQueryWrapper.eq(Design::getId, design.getId());
            Design design1 = designDao.selectOne(designLambdaQueryWrapper);
            design1.setTitle(design.getTitle());
            design1.setDetail(design.getDetail());
            design1.setNumber(design.getNumber());
            design1.setEndDate(design.getEndDate());
            designDao.updateById(design1);
        }else{
            design.setUid(user.getId());
            designDao.insert(design);
        }
        return "redirect:/admin/design/page";
    }

    @RequestMapping("/design/page")
    public ModelAndView page(PageRO<Design> pageRO){
        User loginUser = hostHolder.getUser();
        LambdaQueryWrapper<Design> designLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //老师
        if(loginUser.getUserType() == 2){
            designLambdaQueryWrapper.eq(Design::getUid, loginUser.getId());
        }
        PageRO<Design> designPageRO = designDao.selectPage(pageRO, designLambdaQueryWrapper);
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();

        LambdaQueryWrapper<DesignSelect> designSelectLambdaQueryWrapper = new LambdaQueryWrapper<>();

        designPageRO.getRecords().forEach(design -> {
            User user = userDao.selectOne(userLambdaQueryWrapper.eq(User::getId, design.getUid()));
            List<DesignSelect> designSelects = designSelectDao.selectList(designSelectLambdaQueryWrapper.eq(DesignSelect::getDid, design.getId()));
            design.setExistedNumber(designSelects.size());
            design.setUser(user);
        });
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("page", designPageRO);
        modelAndView.setViewName("/admin/design/list");
        return modelAndView;
    }

    @RequestMapping("/design/detail")
    public ModelAndView designdetail(String id){
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<Design> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Design::getId, id);
        Design design = designDao.selectOne(wrapper);
        if(design == null){
            throw new RuntimeException("用户不存在");
        }
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getId, design.getUid());
        User user = userDao.selectOne(userLambdaQueryWrapper);
        design.setUser(user);
        modelAndView.setViewName("/admin/design/detail");
        modelAndView.addObject("design", design);
        return modelAndView;
    }

    @Autowired
    private DesignSelectDao designSelectDao;

    @RequestMapping("/design/select")
    public String designselect(String id){
        User user = hostHolder.getUser();
        LambdaQueryWrapper<Design> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Design::getId, id);
        Design design = designDao.selectOne(wrapper);
        LambdaQueryWrapper<DesignSelect> designSelectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        designSelectLambdaQueryWrapper.eq(DesignSelect::getUid, user.getId());
        DesignSelect designSelect = designSelectDao.selectOne(designSelectLambdaQueryWrapper);
        if(Objects.nonNull(designSelect)){
            //如果改选的话
            LambdaQueryWrapper<Design> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(Design::getId, designSelect.getDid());
            Design design1 = designDao.selectOne(wrapper1);
            long time = design1.getEndDate().getTime();
            long time1 = new Date().getTime();
            if(time < time1){
                throw new RuntimeException("时间已到无法改选");
            }
            LambdaQueryWrapper<DesignSelect> designSelectLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            designSelectLambdaQueryWrapper1.eq(DesignSelect::getDid, design.getId());
            List<DesignSelect> designSelects = designSelectDao.selectList(designSelectLambdaQueryWrapper1);
            int size = designSelects.size();
            Integer number = design.getNumber();
            if(number < size + 1){
                throw new RuntimeException("人数已满无法改选");
            }
            designSelect.setDid(design.getId());
            designSelectDao.updateById(designSelect);
        }else{
            //第一次选
            DesignSelect ds = new DesignSelect();
            ds.setDid(design.getId());
            ds.setUid(user.getId());
            designSelectDao.insert(ds);
        }

        return "redirect:/admin/design/page";

    }


    @RequestMapping("/myselect/design")
    public ModelAndView myselectdesign(){
        User user = hostHolder.getUser();
        LambdaQueryWrapper<DesignSelect> designSelectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        designSelectLambdaQueryWrapper.eq(DesignSelect::getUid, user.getId());
        DesignSelect designSelect = designSelectDao.selectOne(designSelectLambdaQueryWrapper);

        if(Objects.nonNull(designSelect)){
            LambdaQueryWrapper<Design> designLambdaQueryWrapper = new LambdaQueryWrapper<>();
            designLambdaQueryWrapper.eq(Design::getId, designSelect.getDid());
            Design design = designDao.selectOne(designLambdaQueryWrapper);

            design.setUser(user);

            designSelect.setDesign(design);
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/my/selectdesign");
        modelAndView.addObject("designSelect", designSelect);

        return modelAndView;
    }

    @RequestMapping("/design/exitdesign")
    public String mydesign(String id){
        User user = hostHolder.getUser();

        LambdaQueryWrapper<Design> designLambdaQueryWrapper = new LambdaQueryWrapper<>();
        designLambdaQueryWrapper.eq(Design::getId, id);
        Design design = designDao.selectOne(designLambdaQueryWrapper);
        long time = design.getEndDate().getTime();
        long time1 = new Date().getTime();
        if(time < time1){
            throw new RuntimeException("不可退选");
        }

        LambdaQueryWrapper<DesignSelect> designSelectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        designSelectLambdaQueryWrapper.eq(DesignSelect::getUid, user.getId());
        designSelectLambdaQueryWrapper.eq(DesignSelect::getDid, id);
        DesignSelect designSelect = designSelectDao.selectOne(designSelectLambdaQueryWrapper);
        designSelectDao.deleteById(designSelect);
        return "redirect:/admin/design/page";
    }

}
